<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/6/11
 * Time: 下午1:59
 */

namespace Modules\Admin\Auth\Middleware;

use Closure;
use Modules\Admin\Auth\Facades\AdminAuth;
use App\Models\AdminRole;

class AdminAuthMiddleware
{
    protected $request;

    public function handle($request, Closure $next)
    {
        $this->request = $request;

        if (!AdminAuth::check()) {
            if ($this->request->ajax()) {
                return fail(403,'登录已失效，请重新登录。');
            }
            return redirect()->route('admin_login');
        }
        if (!$this->request->ajax()) {
            $this->getMenu();
        }
        return $this->checkResource($next);
    }

    /**
     * 验证管理员权限
     *
     * @param Closure $next
     *
     * @return mixed
     */
    public function checkResource(Closure $next)
    {
        $user = AdminAuth::user();

        // 超级管理员免检
        if ($user->is_super) {
            return $next($this->request);
        }
        // 获取用户角色拥有的路由列表
        $routes = array_merge(AdminRole::$whitelist, $user->role->getResourceRoutes());

        // 判断当前路由是否包含在列表内
        if (!$this->request->route()->named($routes)) {
            if ($this->request->ajax()) {
                return fail(403,'权限不足。');
            }
            return abort(403, '权限不足');
        }

        return $next($this->request);
    }

    public function getMenu()
    {
        $menus = config('menu.admin');
        $user = AdminAuth::user();
        if ($user->is_super) {
            $userRoutes = null;
        } else {
            $userRoutes = array_merge(AdminRole::$whitelist, $user->role->getResourceRoutes());
        }
        $this->request->merge(['asideActive' => '']);
        $this->request->merge(['path' => '/admin']);
        $this->request->merge(['menus' => $this->getOwnMenuAndFillUrl($menus, $userRoutes)]);
        $this->request->merge(['authuser'=>$user]);
    }

    public function getOwnMenuAndFillUrl($menus, $userRoutes)
    {
        foreach ($menus as $key => &$item)
        {
            if (isset($item['route'])) {
                if ($userRoutes !== null && !in_array($item['route'], $userRoutes)) {
                    unset($menus[$key]);
                }
                $item['url'] = route($item['route']);
                if ($this->request->routeIs($item['route'])) {
                    $this->request->merge(['asideActive' => $key]);
                }
            }
            if (isset($item['child'])) {
                $child = $this->getOwnMenuAndFillUrl($item['child'], $userRoutes);
                if ($child) {
                    $item['child'] = $child;
                } else {
                    unset($menus[$key]);
                }
            }
        }

        return $menus;
    }
}